<template>
  <div class="login-content">
    <el-card class="login-box">
      <div class="login-title">登录</div>
      <el-form :model="formData" :rules="rules" ref="loginFormRef" label-width="80px">
        <el-form-item label="用户名" prop="username">
          <el-input v-model="formData.username" clearable placeholder="请输入用户名" />
        </el-form-item>

        <el-form-item label="密码" prop="password">
          <el-input type="password" v-model="formData.password" show-password clearable placeholder="请输入密码" />
        </el-form-item>

        <el-form-item>
          <el-button type="primary" :loading="isSubmitting" @click="submitForm">登录</el-button>
        </el-form-item>
      </el-form>
    </el-card>
  </div>
</template>

<script setup>
import { ref } from "vue";
import { useRouter } from "vue-router";
import { useStore } from "vuex";
const router = useRouter();
const store = useStore();

const loginFormRef = ref();
const formData = ref({
  username: "",
  password: "",
  token: "token",
});

const rules = ref({
  username: [
    { required: true, message: "请输入用户名", trigger: "blur" },
    // { min: 3, max: 10, message: "用户名长度在 3 到 10 个字符", trigger: "blur" },
    // { pattern: /^[a-zA-Z0-9_-]{3,10}$/, message: "用户名格式不正确", trigger: "blur" },
  ],
  password: [
    { required: true, message: "请输入密码", trigger: "blur" },
    // { min: 6, max: 18, message: "密码长度在 6 到 18 个字符", trigger: "blur" },
    // { pattern: /^[a-zA-Z0-9_-]{6,18}$/, message: "密码格式不正确", trigger: "blur" },
  ],
});
const isSubmitting = ref(false);

const submitForm = async () => {
  if (!loginFormRef.value) return;
  isSubmitting.value = true;
  await loginFormRef.value.validate((valid, fields) => {
    if (valid) {
      console.log("submit!");
      store.dispatch("login", formData.value).then(() => {
        router.push("/");
      })
    } else {
      console.log("error submit!", fields);
    }
    isSubmitting.value = false;
  });
};
</script>

<style scoped lang="scss">
.login-content {
  position: relative;
  width: 100%;
  height: 100%;
  background-color: #8d8383;

  .login-box {
    position: absolute;
    top: 30%;
    left: 55%;
    width: 400px;
    padding: 20px;
    border-radius: 8px;
    box-shadow: 0 2px 10px rgba(0, 0, 0, 0.1);

    .login-title {
      text-align: center;
      margin-bottom: 20px;
    }

    .el-button {
      width: 100%;
      height: 40px;
      line-height: 0;
    }
  }
}
</style>
